package cn.itcast.lucene.test;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class QueryIndex {
    /**
     * 查询文档
     */
    @Test
    public void queryIndexTest() throws IOException {
        //获取索引库读对象
        DirectoryReader reader = DirectoryReader.open(FSDirectory.open(new File("D:\\elasticsearch-kibana\\LuceneCreateIndex")));
        //1、获取查询索引库对象
        IndexSearcher indexSearcher = new IndexSearcher(reader);

        //2、执行查询  query:查询对象  参数二：展示的查询结果数据
        //例如：词条查询，查询公司名称中带有北京的公司
        TermQuery query = new TermQuery(new Term("companyName","北"));
        //3、执行查询，获取查询结果  query:查询对象  参数二：展示的查询结果数据
        TopDocs docs = indexSearcher.search(query, 10);
        int totalHits = docs.totalHits;
        System.out.println("满足条件的总记录数："+totalHits);
        //获取查询结果集
        ScoreDoc[] scoreDocs = docs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            //获取文档id
            int docId = scoreDoc.doc;
            //基于文档id，查询文档对象
            Document document = indexSearcher.doc(docId);
            System.out.println( "id:"+ document.get("id"));
            System.out.println( "companyName:"+ document.get("companyName"));
            System.out.println( "companyAddr:"+ document.get("companyAddr"));
            System.out.println( "salary:"+ document.get("salary"));
            System.out.println( "url:"+ document.get("url"));
            System.out.println("**************************************************************");
        }
    }
}
